package cn.walls1717.wallsmall.auth.controller;

import cn.walls1717.wallsmall.auth.component.GiteeHttpClient;
import cn.walls1717.wallsmall.auth.config.GiteeLoginPropertiesConfig;
import cn.walls1717.wallsmall.auth.feign.MemberFeignService;
import cn.walls1717.wallsmall.auth.vo.SocialUserVO;
import cn.walls1717.wallsmall.common.utils.R;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 第三方登录
 *
 * @author walls1717
 * @since 2022/11/13 10:18
 **/
@Controller
@Slf4j
public class OAuth2Controller {
    @Resource
    private GiteeLoginPropertiesConfig propertiesConfig;
    @Resource
    private MemberFeignService memberFeignService;

    /** gitee授权回调 */
    @GetMapping("/gitee/success")
    public String success(HttpServletRequest request, HttpSession session) throws Exception {
        // 得到Authorization Code
        String code = request.getParameter("code");

        // 通过Authorization Code获取Access Token
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code" + "&client_id="
            + propertiesConfig.getClientId() + "&client_secret=" + propertiesConfig.getClientSecret() + "&code=" + code
            + "&redirect_uri=" + propertiesConfig.getUrl();
        JSONObject accessTokenJson = GiteeHttpClient.getAccessToken(url);

        assert accessTokenJson != null;
        if (accessTokenJson.get("error_description") != null) {
            return "redirect:http://auth.wallsmall.com/login.html";
        }

        // 获取用户信息
        url = "https://gitee.com/api/v5/user?access_token=" + accessTokenJson.get("access_token");
        JSONObject jsonObject = GiteeHttpClient.getUserInfo(url);
        // 获取到用户信息之后，就该写你自己的业务逻辑了
        SocialUserVO socialUserVO = new SocialUserVO();
        socialUserVO.setId(jsonObject.get("id").toString());
        socialUserVO.setName(jsonObject.get("name").toString());
        R r = memberFeignService.socialLogin(socialUserVO);
        if (r.getCode() != 0) {
            return "redirect:http://auth.wallsmall.com/login.html";
        }
        // MemberRespVO data = (MemberRespVO)r.get("data");
        Object data = r.get("data");
        log.info("data -> {}", data);
        session.setAttribute("loginUser", data);
        return "redirect:http://wallsmall.com";
    }
}
